import sys
import time
from os import mkdir
from os.path import (abspath, dirname, join, isdir)
from datetime import date
import argparse

def defaultfilename():
    """设置默认日志目录"""
    dir_log = 'logfile'
    filename = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) + '.log'
    path = dirname(abspath(__file__))  # 获取运行文件路径
    dir_path = join(dirname(path), dir_log)
    if not isdir(dir_path):
        mkdir(dir_path)
    return join(dir_path, filename)


class Logger(object):
    def __init__(self, filename=defaultfilename(), stream=sys.stdout):
        """
        初始化参数并打开日志文件
        :param filename:
        :param stream:
        """
        self.terminal = stream
        # 打开日志文件，追加日志记录
        self.log = open(filename, 'a+', encoding='utf-8')
        self.time = None

    def logging(self, level, message):
        """日志打印模板

        Args:
            level ([str]): 日志等级
            message ([str]): 日志信息
        """
        self.get_time()
        level_list = ["INFO", "WARN", "DEBUG", "ERROR"]
        log_level = level.upper()

        if level.upper() not in level_list:
            sys.exit(1)

        if log_level in ["INFO", "WARN"]:
            log_level = level.upper() + " "
        self.terminal.write(
            "%s - %s - %s\n"
            % (time.asctime(time.localtime(time.time())), log_level, message)
        )
        self.log.write(
            "%s - %s - %s\n"
            % (time.asctime(time.localtime(time.time())), log_level, message)
        )

    def get_time(self):
        """
        输出时间格式化
        :return:
        """
        self.time = time.asctime(time.localtime(time.time()))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="manual to this script")
    parser.add_argument("--level", type=str, default="info")
    parser.add_argument(
        "--message", type=str, default="Developer does not write the log messages."
    )
    args = parser.parse_args()
    log = Logger()
    log.logging(args.level, args.message)
